# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from bottle import Bottle, run
from bottle_sqlite import SQLitePlugin
import json
import paho.mqtt.client as mqtt
import libs.computer as computer

app = Bottle()
mqttc = mqtt.Client()
topic = "iot/system_monitor"
system = computer.getSystemInfo()

app.install(SQLitePlugin(dbfile='/db/test.db'))

@app.route('/')
def default():
    return "Hello World!"

@app.error(404)
def error404(error):
    return 'Nothing here, sorry!'

def on_connect(client, userdata, flags, rc):
	print("Connected with result code "+str(rc))
	mqttc.subscribe(topic)
mqttc.on_connect = on_connect

def on_message(client, userdata, msg):
	print("Received message '" + str(msg.payload) + "' on topic '" + msg.topic + "' with QoS " + str(msg.qos))
mqttc.on_message = on_message

def on_subscribe(client, userdata, mid, granted_qos):
	mqttc.publish(topic, json.dumps({"system": system,"say": "Hello,anyone!"}))
mqttc.on_subscribe = on_subscribe

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection.")
mqttc.on_disconnect = on_disconnect

mqttc.connect("mqtt.maxws.com", 1883, 10)
#mqttc.loop_forever()
mqttc.loop_start()

run(app, host='localhost', port=3388, debug=True, reloader=True)